package com.example.SpringBootDemo.controller;


import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.catalina.Session;
import org.springframework.web.bind.annotation.*;

import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Arrays;

@RequestMapping("/cookie")
@RestController
public class CookieController {
    // 这个可以一次性拿到全部cookie
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
//       if(cookies != null) {
//           for(Cookie cookie : cookies) {
//               System.out.println(cookie.getName() + ":" + cookie.getValue());
//           }}
        Arrays.stream(cookies).forEach(cookie -> {
            System.out.println(cookie.getName() + ": " + cookie.getValue());
        });
       return "原始方法获取cookie成功";
    }
    // 这个只能拿到单个cookie 根据业务情况来决定使用哪一个
    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("name") String name,@CookieValue("age") String age) {
        return "String获取cookie成功  " + name + ": " + age;
    }
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request) {
       HttpSession session = request.getSession();
       session.setAttribute("username","zhangsan");
        return "添加session成功";
    }
    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if(session != null) {
            String username = (String) session.getAttribute("username");
            return "获取session值username: " + username;
        }
        return "session 为空";
    }
    // string 获取session的方法, 这里的 false 是设置为非必传,否则就是必传
    @RequestMapping("/getSession2")
    public String getSession2(@SessionAttribute(required = false) String username) {
        return "登入用户: " + username;
    }
    // 这里的获取,是等于 HttpSession session = request.getSession(true);
    @RequestMapping("/getSession3")
    public String getSession3(HttpSession session) {
        String username = (String) session.getAttribute("username");
        return "获取session值username: " + username;
    }
    // 传统方法
    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request) {
        // 获取浏览器版本信息
        String UserAgent = request.getHeader("User-Agent");
        return "UserAgent: " + UserAgent;
    }
    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String UserAgent) {
        // 获取浏览器版本信息
        return "UserAgent: " + UserAgent;
    }
}
